package org.objective.dal;

import java.io.Serializable;
import org.common.dynamicbean.DynamicBean;
import org.objective.base.BaseField;

/**
 *
 * @author gus
 */
public final class RowValue implements Serializable
{
    private final static long serialVersionUID = -723467237895114L;
    private final long objectId;
    private final DynamicBean originalBean;
    private DynamicBean currentBean;
    private boolean changed = false;
    private boolean dirty = false;

    RowValue( long objectId, DynamicBean bean ) throws Exception
    {
        this.objectId = objectId;
        this.originalBean = bean;
        this.currentBean = (DynamicBean) bean.clone();
    }

    public <T> T getValue( BaseField field, boolean original )
    {
        if ( original )
        {
            return originalBean.<T>getValue(field.getName());
        }
        return currentBean.<T>getValue(field.getName());
    }

    public <T> T getValue( BaseField field )
    {
        return (T) getValue(field, false);
    }

    public <T> void setValue( BaseField field, T value )
    {
        Class fieldType = currentBean.getType(field.getName());
        if ( !fieldType.isAssignableFrom(value.getClass()) )
        {
            throw new IllegalArgumentException(String.format("[value] incompatible type required [%s]  found [%s]", fieldType, value.getClass())) ;
        }
        currentBean.setValue(field.getName(), value);
        dirty = true;
    }

    public boolean isChanged()
    {
        return changed;
    }

    public boolean isDirty()
    {
        return dirty;
    }

    public synchronized void commitChange()
    {
        changed = dirty;
        dirty = false;
    }

    public synchronized void rollbackChange() throws Exception
    {
        currentBean = (DynamicBean) originalBean.clone();
        dirty = false;
        changed = false;
    }
}
